package com.welisit.test.manager;

import com.welisit.test.model.AepTimerQuartzConfig;
import com.welisit.test.service.TimerManagerService;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.scheduling.quartz.CronTriggerBean;

import java.util.ArrayList;
import java.util.List;

/**
 * @author welisit
 * @create 2022-04-22 16:15
 */
public class QuartzManager implements BeanFactoryAware {
    private Logger log = Logger.getLogger(QuartzManager.class);
    private Scheduler scheduler;
    private TimerManagerService service;
    private static BeanFactory beanFactory = null;

    public TimerManagerService getService() {
        return service;
    }

    public void setService(TimerManagerService service) {
        this.service = service;
    }

    public void reScheduleJob() {
        List<AepTimerQuartzConfig> allList = new ArrayList<>();
        //查询数据库里计划任务来配置计划任务
        List<AepTimerQuartzConfig> quartzList = service.getQuartzConfig();
        allList.addAll(quartzList);
        log.info("查询到任务的个数：" + allList.size());
        if (allList != null && allList.size() > 0) {
            for (AepTimerQuartzConfig tbcq : allList) {
                configQuatrz(tbcq);
            }
        }
    }

    /**
     * 处理数据库查询出的定时任务
     *
     * @param tbcq
     * @return
     */
    public boolean configQuatrz(AepTimerQuartzConfig tbcq) {
        try {
            // 运行时可通过动态注入的scheduler得到trigger
            CronTriggerBean trigger = (CronTriggerBean) scheduler.getTrigger(tbcq.getTriggername(), Scheduler.DEFAULT_GROUP);
            scheduler.getTriggerGroupNames();
            scheduler.getTriggerListenerNames();
            List<JobExecutionContext> list = scheduler.getCurrentlyExecutingJobs();
            list.size();
            scheduler.getGlobalTriggerListeners();
            scheduler.getGlobalJobListeners();
            scheduler.toString();
            // 如果计划任务已存在则调用修改方法
            if (trigger != null) {
                service.change(tbcq, trigger, scheduler);
            } else {
                // 如果计划任务不存在并且数据库里的任务状态为可用时,则创建计划任务
                if (tbcq.getState().equals("1")) {
                    System.out.println("创建任务：------------" + tbcq.getJobdetailname());
                    service.createCronTriggerBean(tbcq, scheduler, beanFactory);
                }
            }
            return true;
        } catch (Exception e) {
            log.info("执行【" + tbcq.getTriggername() + "】出错：" + e.getMessage());
        }
        return false;
    }

    public void setScheduler(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    public void setBeanFactory(BeanFactory factory) throws BeansException {
        this.beanFactory = factory;
    }
}